In [12]:
#### Interpreter as a calculator
2+2
Out[12]:
In [13]:
# interpreter as a programming language
width =10
height = 45
width*height
Out[13]:
In [89]:
#use answer as an argument (_)
_/45
Out[89]:
In [90]:
# strings, excape character \ and different quotes ' '' ''' "
print('"doesn\'t it ?", he said.')
In [91]:
# by adding (r) you can use raw strings. \n means new line
print(r'C:\some\name','\n','C:\some\name')
In [92]:
#span string litterals span multiple lines """...""" or '''...'''.
#If you add \ at the end of a line it prevents new line.
print("""
What a wonderful world isn\'t it ?
Lol, it simply isn\'t!
""")
In [93]:
# it is possible to use some limited math while gluing strings
2*'a'+5*'i'+3*'!'
Out[93]:
In [94]:
'Py'+'thon'
Out[94]:
In [95]:
#strings are immutable word[4]=r gives an error #strings are immutable
word='sunny'
word[1:3]
word[2:]
Out[95]:
In [96]:
# by assignment lists are not copied only its pointer is assigned however a slice
# lets you copy the value of a list
squares = [1, 4, 9, 16, 25]
boxes=squares
quadras = squares[:]
squares[3]=0
boxes
Out[96]:
In [97]:
quadras
Out[97]:
In [98]:
#list itself is a class there are alot of methods for it
quadras.append(202)
quadras.sort()
quadras
Out[98]:
In [99]:
quadras.reverse()
quadras
Out[99]:
In [100]:
# Here comes loops for fibonacci series
a,b=1,10
while a<b :
print (a)
if a<b/2 :
print('a is smaller than half of b')
elif a==b/2:
print ('a is equal to the half of b')
else:
print ('a is larger than half of b')
a=a+1
In [101]:
# a for loop example
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
print(i, a[i])
In [102]:
# there are interesting break continue and pass statements in loops
# while break and continue are obvious pass is passed when an argument needed
# syntactically
class MyEmptyClass:
pass #remember to impletement this
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
In [103]:
# Defining funtions with a return value
def fib(n): # write Fibonacci series up to n
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end=',')
a, b = b, a+b
print()
return(b-a)
fib(5000)
Out[103]:
In [104]:
#where is my function in memory
func=fib
func
Out[104]:
In [105]:
# small anonymous functions can be created using lambda
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
pairs
Out[105]:
In [106]:
# Unpacking Arguments using * for list and ** for dictionaries
def concat(*args, sep="/"):
return sep.join(args)
print(concat('a','b','c'))
def aFunc(what="I dont know",this=" this item"):
print(what,this)
d={"what":"My parrot","this":"is a green bird "}
aFunc(**d)
In [107]:
# there are default arguments values and keyword arguments
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print("-- This parrot wouldn't", action, end=' ')
print("if you put", voltage, "volts through it.")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")
parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
# these wouldn't work !
# parrot() # required argument missing
# parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument
# parrot(110, voltage=220) # duplicate value for the same argument
# parrot(actor='John Cleese') # unknown keyword argument
In [108]:
squares = list(map(lambda x: x**2, range(10)))
squares = [x**2 for x in range(10)]
squares
Out[108]:
In [109]:
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
Out[109]:
In [110]:
[x**3 for x in range(5,20,3)]
Out[110]:
In [111]:
t = range(1,5),'xero',231/2 # a tuple is immutable
print(t)
In [112]:
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} # is a set
print(basket)
In [113]:
a=set('gediz gürsu') # a set reduces to unique letters ...
b=set('giresun')
print(a,a|b,a^b,a-b)
In [178]:
mydict=dict(sape=4139, guido=4127, jack=4098) # dictionary is a basic data type
{x: x**2 for x in (2, 4, 6)}
Out[178]:
In [115]:
# lists can be used as different data types such as stacks queues
from collections import deque #faster operations ...
queue = deque(["Eric", "John", "Michael"])
queue.popleft()
queue
Out[115]:
In [155]:
# matrix transposition
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],]
[[row[i] for row in matrix] for i in range(4)]
Out[155]:
In [156]:
list(zip(*matrix)) #
Out[156]:
In [162]:
%%HTML
<h1 style="color:blue;font-family:verdana;font-size:16px">This is my Design</h1>
In [157]:
del matrix[0]
matrix
Out[157]:
In [158]:
t = 12345, 54321, 'hello!',matrix #tuples are useful I guess ...
t
Out[158]:
In [183]:
for i in enumerate(reversed(t)):
print(i)
print ('\n')
for i,j in mydict.items():
print(i,j)
In [190]:
#modules fibo.py __name__ as global variable
if __name__ == "__main__":
import sys
# fib(int(sys.argv[1])) #to use fibo.sys as script do the following
# >>> python fibo.py 50 #to use it from command prompt
# When a module is it first looks for the standard modules then for .py
sys.path.append("""C:/Users/gediz/Documents""")
sys.path
Out[190]:
In [193]:
import builtins
dir(builtins)
Out[193]:
In [196]:
# import sound.effects.echo
# from sound.effects import echo
# from sound.effects.echo import echofilter
# from sound.effects import *
# if package has __all__ as __all__ = ["echo", "surround", "reverse"]
# then * imports these submodules
In [198]:
print('{0} and {1}'.format('spam', 'eggs'))
print('We are the {} who say "{}!"'.format('knights', 'Ni'))
for x in range(1, 11):
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
In [1]:
f = open('workfile', 'r+') # w r r+ a b-> binary other than text files
f.write('This is a test\n')
f.readline()
Out[1]:
In [11]:
f.seek(5) # go to the 5th byte or binary ...
f.read(9)
Out[11]:
In [205]:
f.tell() # current position in file
Out[205]:
In [217]:
f.close()
f.closed
Out[217]:
In [228]:
import json
json.dumps([1,2,3])
f = open('workfile', 'r+')
json.dumps([1,2,3],f)
Out[228]:
In [224]:
f.closed
Out[224]:
In [229]:
raise NameError('HiThere')
In [236]:
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("executing finally clause")
divide (5,0)
In [237]:
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
x = MyClass()
In [245]:
x.f()
Out[245]:
In [246]:
x.counter=100
x.counter
Out[246]:
In [248]:
# instance variables in class default namespace is shared by instances (strangely)
# therefore each variable regarding to this instance should be located under _init_
class Dog:
def __init__(self, name):
self.name = name
self.tricks = [] # creates a new empty list for each dog
def add_trick(self, trick):
self.tricks.append(trick)
d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll over')
e.add_trick('play dead')
e.tricks
Out[248]:
In [257]:
class mytestclass:
def __init__(self,name):
self.name=name
self.tests=[]
def add_test(self,test):
self.tests.append(test)
myclass = mytestclass('first test')
myclass.add_test('testere')
myclass.tests
Out[257]:
In [263]:
class myoverrideclass(mytestclass): #overriding overloading functions ...
def add_test(self,test): #overriding works
print('this is an overriden class')
# def add_test(self,test1,test2): # overloading does not work
# self.tests.append(test1)
# self.tests.append(test2)
myclass = myoverrideclass('test2')
myclass.add_test('testere')
myclass.tests
Out[263]:
In [267]:
%%HTML
<h1 style="color:red;font-family:verdana;font-size:16px">
Overloading is not required since we able to omit arguments </h1>
<a href="http://stackoverflow.com/questions/10202938/how-do-i-use-method-overloading-in-python">
Visit Stackoverflow subject </a>
In [ ]:
# Help and lookup functions and system functions...
# import os
# print(dir(sys))
# help(os)
# import pip
# help(pip)
In [26]:
%lsmagic
Out[26]:
In [12]:
%cls?
In [28]:
from IPython.display import HTML, SVG, YouTubeVideo
YouTubeVideo('j9YpkSX7NNM')
Out[28]:
In [36]:
In [ ]: